import React, { useState } from 'react'
import { Toast, NavBar } from 'react-vant';
import { Button, Input, Form, Notify } from 'react-vant'
import { sendCode, checkCode } from '@/models'
import { useNavigate, useLocation } from 'react-router-dom';

export default function Step1() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  let location = useLocation()
  let { tel } = location.state
  let [disabled, setDisabled] = useState('disabled')
  let [ban, setBan] = useState('')
  let [time, setTime] = useState(5)
  const onFinish = values => {
    values.tel = tel
    console.log(values)
    checkCode(values).then(res => {
      console.log(res);
      if (res.code === '200') {
        Notify.show({ type: 'success', message: res.message })
        navigate('/regist/step3', { state: { tel } })
      } else {
        Notify.show({ type: 'danger', message: res.message })
      }
    })
  }
  let timer = null
  const CountDown = () => {
    if (time === 0) {
      setTime(5)
      setBan('')
      clearTimeout(timer);
    } else {
      time--
      setTime(time)
      timer = setTimeout(() => {
        CountDown()
      }, 1000)
    }
  }
  const send = () => {
    sendCode(tel).then(res => {
      console.log(res);
      setBan('disabled')
      CountDown()
    })
  }

  const input = (val) => {
    if (val.length >= 5) {
      setDisabled('')
    }
  }
  return (
    <div>
      <NavBar
        title="注册"
        leftText="返回"
        onClickLeft={() => navigate(-1)}
        style={{ marginBottom: '20px', backgroundColor: '#fff', borderBottom: '1px solid #ccc' }}
      />
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div style={{ margin: '16px 16px 0' }}>
            <Button disabled={disabled} round nativeType='submit' type='primary' block>
              下一步
            </Button>
          </div>
        }
      >
        <Form.Item
          rules={[{ required: true, message: '请填写验证码' }]}
          name='telcode'
          label='短信验证码'
          suffix={<Button size="small" type="primary" disabled={ban} onClick={send}>{ban === '' ? '发送' : time + '秒后再次发送'}</Button>}
        >
          <Input onChange={input} placeholder='请输入验证码' />
        </Form.Item>
      </Form>

    </div>
  )
}
